const app = getApp();
let pageNo = 1;
let pageSize = 10;
var url = app.data.url;
var platFormUrl = app.data.platFormUrl;
var util = require('../../utils/util.js');
var date = util.formatDate(new Date().getTime());
var time = util.formatTime(new Date().getTime());
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    contentList: [1,2],
    queryType:'',
    orderType: 'GOODS', //默认商家商品
    itemName: "",
    id: "",
    price : 0,
    disabledStatus: false,
    displayDate: date,
    displayTime: time,
    relationName: '',
    relationPhone: '',
    uuid: app.globalData.openId,
    jsonData: '',
    modelId: 'jY9ixz8CDDdFSpeOuYqS4hlQzG7wo5K_YpVxU88bCf0',
    template_model_id: '0BnoZDpPF4Khi8MY55xCxba74yd3nhG5mK2CmnhRzKE',
    isShareByJielong: 'N',
    jielongPayOrderId: '',


    imgUrls: [     "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2F747a12d76b114bfb2ccccfe5cd0b555f3a5edc9c.jpg&refer=http%3A%2F%2Fi0.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=6364d9d98c5a1fe232d5157d8f432b26",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Farchive%2F84d030256c18e040683507c1289a4a439b13ccb1.png&refer=http%3A%2F%2Fi1.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=6639baa2c782848981f53888ef684991",
      
    ],

    is_shoucang: 0,
    goods_img: [
      { 'img': 'https://ss2.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/f636afc379310a555e97e0c0b54543a982261056.jpg' },
      { 'img': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Farchive%2F84d030256c18e040683507c1289a4a439b13ccb1.png&refer=http%3A%2F%2Fi1.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=6639baa2c782848981f53888ef684991' },
      { 'img': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2F747a12d76b114bfb2ccccfe5cd0b555f3a5edc9c.jpg&refer=http%3A%2F%2Fi0.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=6364d9d98c5a1fe232d5157d8f432b26' },
      { 'img': 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg35.51tietu.net%2Fpic%2F2016-121501%2F20161215010005yh4kuhg1uot316190.jpg&refer=http%3A%2F%2Fimg35.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=496578feb90fb4b8070e3f468fc81578' },
    ],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    pjDataList: [{ headpic: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg', author: '张三', add_time: '2018-06-01', content: '好评好评，真实太好了!' },
    { headpic: 'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg', author: '张三', add_time: '2018-06-01', content: '好评好评，真实太好了!' }
    ],//评价数据
    detailImg: [
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg35.51tietu.net%2Fpic%2F2016-121501%2F20161215010005yh4kuhg1uot316190.jpg&refer=http%3A%2F%2Fimg35.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=496578feb90fb4b8070e3f468fc81578",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farticle%2F747a12d76b114bfb2ccccfe5cd0b555f3a5edc9c.jpg&refer=http%3A%2F%2Fi0.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=6364d9d98c5a1fe232d5157d8f432b26",
      "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fi1.hdslb.com%2Fbfs%2Farchive%2F84d030256c18e040683507c1289a4a439b13ccb1.png&refer=http%3A%2F%2Fi1.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1630421831&t=6639baa2c782848981f53888ef684991",
     
    ],

  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.info(options);
    that.setData({
      id: options.id,
      itemName: options.name,
      queryType: '1',
      merchantId: options.merchantId,
      price: options.payType == 0 ? options.originalprice :  options.discountprice
    })  
    // 查询封面图 ，详情图
    that.queryImgForItem(options.id);
  },

  /**查询封面图，详情图 */
  queryImgForItem: function (id){
    let _that = this;
    wx.request({
      url: platFormUrl + '/MerchantApi/client/noAuth/queryItemImg',
      data: {
        id: id
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res);
        if (res.data.code == 200) {
          let item = res.data.data;
          _that.setData({
            imgUrls: item.coverList,
            detailImg: item.detailList
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }
      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      loading: false,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _that = this;
    _that.setData({
      disabledStatus: false
    })

    let orderType = _that.data.orderType;
    wx.getStorage({
      key: "openId",
      success(res) {
        _that.setData({
          uuid: res.data
        })
        //if (orderType != 'IN_HALL') {
        if (true) {
          wx.request({
            url: url + '/CommonRelationApi/queryCommonRelationByUuid',
            data: {
              uuid: res.data
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log(res);
              if (res.data.code == 200) {
                let item = res.data.data;
                _that.setData({
                  relationName: item.name,
                  relationPhone: item.phone
                })
              } else if (res.data.code == 500) {
                // 尚未登录
                Dialog.confirm({
                  title: '提示',
                  message: '您当前尚未登录, 请点击确认跳转登录页面!'
                }).then(() => {
                  // on confirm
                  wx.navigateTo({
                    url: "../../pages/login/index"
                  })
                }).catch(() => {
                  // on cancel
                });
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
                _that.setData({
                  relationName: '',
                  relationPhone: ''
                })
              }
            },
            fail: function (res) {
              console.info('submit fail');
            },
            complete: function (res) {
              console.info('submit complete');
            }
          })
        }

      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    
  },

  /***
   * 自动接单
   */
  autoAccept: function (orderId, orderType) {
    let _that = this;
    let merchantId = _that.data.merchantId;
    //let merchantId = 15;
    wx.request({
      url: url + '/OrderApi/checkAutoAccept',
      data: {
        merchantId: merchantId,
        orderType: orderType
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        if (res.data.code == 200) {
          // 自动接单
          wx.request({
            url: url + '/PrintApi/print',
            data: {
              orderId: orderId,
              merchantId: merchantId
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: function (e) {
              console.log("自动接单");
            }
          })
        }
      }
    })

  },

  onSubmit: function (options) {
    let _that = this;
    //点击支付,禁用按钮,防止多次点击
    _that.setData({
      disabledStatus: true
    })
    let wxUserUuid = app.globalData.openId;
    let relationName = _that.data.relationName;
    let relationPhone = _that.data.relationPhone;
    let merchantId = _that.data.merchantId;
    //let merchantId = 15;
    let jsonData = new Object();
    let orderType = _that.data.orderType;
    let mark = _that.data.mark;
    let queryType = _that.data.queryType;
    let inHallPreMenu = _that.data.inHallPreMenu;
    let payonline = _that.data.payonline;  
    console.info(jsonData);
    jsonData.timeVal = _that.data.displayDate + " " + _that.data.displayTime;
    jsonData.relationName = relationName;
    jsonData.relationPhone = relationPhone;
    jsonData.totalPrice = _that.data.price;
    jsonData.name = _that.data.itemName;
    jsonData.merchantId = merchantId;
    var item = [];
    var itemObj = new Object();
    itemObj.id = 0;
    itemObj.title = _that.data.itemName;
    itemObj.num = 1;
    itemObj.price = _that.data.price;
    itemObj.itemType = 0;
    itemObj.order = 1;
    item[0] = itemObj;
    jsonData.itemApi = JSON.stringify(item);
    jsonData.isShareByJielong = 'N';
    if (!jsonData.token) {
      jsonData.token = _that.data.uuid;
    }
    jsonData.orderType = 'GOODS';
    jsonData.queryType = 7;
  
    console.log("jsonData");
    console.info(jsonData);

    //支付
    wx.request({
      url: url + '/OrderApi/insertOrder',
      data: jsonData,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        let orderId = res.data.data;
        if (res.data.code == 200) {
          wx.request({
            url: url + '/OrderApi/updateNameAndPhoneByOrderId',
            data: {
              orderId: orderId,
              name: relationName,
              phone: relationPhone
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
              console.log("发起支付1");
              if (res.data.code == 200) {
                // 发起支付
                console.log("发起支付2");
                console.log(wxUserUuid);
                console.log(orderId);
                console.log(merchantId);
                wx.requestSubscribeMessage({
                  tmplIds: [_that.data.modelId, _that.data.template_model_id],
                  success(res) {
                    wx.request({
                      url: url + '/WeChatPayApi/servicePrePay',
                      data: {
                        uuid: wxUserUuid,
                        orderId: orderId,
                        merchantId: merchantId,
                        isShareByJielong: _that.data.isShareByJielong,
                        jielongPayOrderId: _that.data.jielongPayOrderId
                      },
                      method: 'POST',
                      header: {
                        'content-type': 'application/x-www-form-urlencoded'
                      },
                      success: function (res) {
                        console.log("发起支付3");
                        console.log(res.data.code);
                        if (res.data.code == 200) {
                          // 发起支付
                          let item = res.data.data;
                          let wxPaymentPojo = item.wxPaymentParamPojo;
                          wx.requestPayment({
                            'timeStamp': wxPaymentPojo.timeStamp,
                            'nonceStr': wxPaymentPojo.nonceStr,
                            'package': wxPaymentPojo.packageStr,
                            'signType': 'MD5',
                            'paySign': wxPaymentPojo.paySign,
                            'success': function (res) {
                              console.log("发起支付4");
                              console.log(res);
                              // 是否自动接单
                              _that.autoAccept(orderId, orderType);
                              // 支付成功, 更新订单状态
                              let jsonParam = JSON.stringify(item.stringStringMap);

                              wx.request({
                                url: url + '/WeChatPayApi/insertWxPay',
                                data: {
                                  jsonParam: jsonParam
                                },
                                method: 'POST',
                                header: {
                                  'content-type': 'application/x-www-form-urlencoded'
                                },
                                success: function (res) {
                                  console.log("发起支付5");
                                  if (res.data.code == 200) {
                                    wx.request({
                                      url: url + '/WeChatPayApi/updatePreOrderStatusByOrderId',
                                      data: {
                                        orderId: orderId
                                      },
                                      method: 'POST',
                                      header: {
                                        'content-type': 'application/x-www-form-urlencoded'
                                      },
                                      success: function (res) {
                                        console.log("发起支付6");
                                        if (res.data.code == 200) {
                                          // 支付成功, 发送消息
                                          wx.request({
                                            url: url + '/WeChatPayApi/toSendMessage',
                                            data: {
                                              orderId: orderId,
                                              wxUserUuid: wxUserUuid
                                            },
                                            method: 'POST',
                                            header: {
                                              'content-type': 'application/x-www-form-urlencoded'
                                            },
                                            success: function (res) {
                                              console.log("发送订阅消息:" + res);
                                            }
                                          })

                                          // 发送模板消息
                                          wx.request({
                                            url: url + '/WeChatPayApi/sendModelMms',
                                            data: {
                                              orderId: orderId,
                                              wxUserUuid: wxUserUuid
                                            },
                                            method: 'POST',
                                            header: {
                                              'content-type': 'application/x-www-form-urlencoded'
                                            },
                                            success: function (res) {
                                              console.log("发送模板消息:" + res);
                                            }
                                          })


                                          // 跳转订单支付成功页面
                                          wx.reLaunch({
                                            url: '../../pages/pay-detail/index?orderId=' + orderId + "&queryType=" + _that.data.queryType + "&isShareByJielong=" + _that.data.isShareByJielong + "&jielongPayOrderId=" + _that.data.jielongPayOrderId
                                          })
                                        } else {
                                          wx.showToast({
                                            title: res.data.msg,
                                            icon: "none",
                                            duration: 2000
                                          })
                                        }
                                      }
                                    })

                                  } else {
                                    wx.showToast({
                                      title: res.data.msg,
                                      icon: "none",
                                      duration: 2000
                                    })
                                  }
                                }
                              })

                            },
                            'fail': function (res) {
                              console.log("支付失败!");
                              console.log(res);
                            },
                            'complete': function (res) {
                              console.log("方法调用结束");
                              console.log(res);
                            }
                          })
                        } else {
                          wx.showToast({
                            //title: res.data.msg,
                            title: '什么情况',
                            icon: "none",
                            duration: 2000
                          })
                        }

                      },
                      fail: function (res) {
                        console.info('submit fail');
                      },
                      complete: function (res) {
                        console.info('submit complete');
                      }
                    })
                  }, fail(res) {
                    console.info("发送模板信息失败");
                  }, complete(res) {
                    console.info("来咯");
                  }
                })
              } else {
                wx.showToast({
                  title: res.data.msg,
                  icon: "none",
                  duration: 2000
                })
              }
            },
            fail: function (res) {
              console.info('submit fail');
            },
            complete: function (res) {
              console.info('submit complete');
            }
          })
          /*}*/

        } else if (res.data.code == 500) {
          //尚未登录
          Dialog.confirm({
            title: '提示',
            message: '您当前尚未登录, 请点击确认跳转登录页面!'
          }).then(() => {
            // on confirm
            wx.navigateTo({
              url: "../../pages/login/index"
            })
          }).catch(() => {
            // on cancel
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none",
            duration: 2000
          })
        }

      },
      fail: function (res) {
        console.info('submit fail');
      },
      complete: function (res) {
        console.info('submit complete');
      }

    })
        
    


  },




  //新添加
  previewImage: function (e) {
    var current = e.target.dataset.src;

    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: this.data.imgUrls // 需要预览的图片http链接列表  
    })
  },

})